#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<mysql/mysql.h>

typedef struct student
{
	int code;
	char name[10];
	int age;
	struct student *next;
}STU;

STU *creat_list(void);
void display(STU *head);
void seve(STU *head);
void mylist_free(STU*head);

int main()
{
	STU * head = NULL;
	head = creat_list();

	display(head);
	
	mylist_free(head);

	return 0;
}
//创建
STU *creat_list(void)
{
	STU *head=(STU*)malloc(sizeof(STU));
	memset(head,0,sizeof(STU));
	STU *end=head;
	int ret=0;
	STU *temp = head->next;

	char str[100] ={0};
	MYSQL *con = NULL;
	MYSQL *res = NULL;
	//初始化链接句柄
	con = mysql_init(NULL);
	//链接数据库
	res = mysql_real_connect(con,"localhost","root","","emp",0,NULL,0);//句柄，本地数据库，用户名，密码，库名，0，NULL，0
	if(res == NULL)
	{
		printf("%s\n",mysql_error(con));
		return head;
	}
	printf("connect is success\n");

	//组织语句
	strcpy(str,"select * from student");
	//将查询语句送到mysql执行
	ret = mysql_query(con,str);
	if(ret != 0)
	{
		printf("%s\n",mysql_error(con));
		mysql_close(con);
		return head;
	}
	//?不释放不能执行其他sql语句

	MYSQL_RES *res1 = NULL;
	MYSQL_ROW row = NULL;
	//将表中所有数据下载的到内存
	//res1 = mysql_use_result(con);
	res1 = mysql_store_result(con);

	if(res1 == NULL)
	{
		printf("%s\n",mysql_error(con));
		mysql_close(con);
		exit(-1);
	}

	row = mysql_fetch_row(res1);
	while(row != NULL )
	{

		STU *temp = (STU*)malloc(sizeof(STU));
		memset(temp,0,sizeof(STU));
		//转换年龄和code，并将所有数据输入到结构体中
		sscanf(row[0],"%d",&temp->code);
		strcpy(temp->name,row[1]);
		sscanf(row[2],"%d",&temp->age);
		temp->next = NULL;

		end->next = temp;
		end = end->next;


		row = mysql_fetch_row(res1);
	}
	printf("!!!\n");
	//关闭文件
	mysql_free_result(res1);
	
	mysql_close(con);

	return head;
}
//查看
void display(STU *head)
{
	STU * temp = head->next;

	while(temp != NULL)
	{
		printf("%d %s %d\n",temp->code,temp->name,temp->age);
		temp = temp->next;
	}
}

void mylist_free(STU*head)
{
	STU *temp = head;
	STU *end = head;
	
	while(end != NULL)
	{
		end = temp->next;
		free(temp);
		temp = end;
	}
}

